package TreeSeries;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class LevelOrderByIterativeSolution_102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        // 使用迭代法 辅助队列实现
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        queue.offer(root);

        while (!queue.isEmpty()) {
            int queueSize = queue.size();
            List<Integer> res = new ArrayList<>();

            for (int i = 0; i < queueSize; i++) {
                TreeNode tempNode = queue.poll();
                res.add(tempNode.val);

                if (tempNode.left != null) queue.offer(tempNode.left);
                if (tempNode.right != null) queue.offer(tempNode.right);
            }
            result.add(res);
        }
        return result;
    }
}
